﻿package fpc.controls.buttons;
import fpc.changers.Changer;
import fpc.utils.WrappedDictionary;

class RadioButtonGroup< T > extends Changer<T>
{
	var _valueByButton:WrappedDictionary<IButton, T>;
	
	public function new(listener:T->Dynamic = null) 
	{
		super(listener);
		add(onChange);
		_valueByButton = new WrappedDictionary();
		_clickLevel = 0;
	}
	
	public function addButton(button:IButton, value:T)
	{
		_valueByButton.set(button, value);
		button.heraldClick.add(onClick);
	}
	
	public function removeButton(button:IButton)
	{
		_valueByButton.delete(button);
		button.heraldClick.remove(onClick);
	}
	
	var _clickLevel:Int;
	
	function onClick(button:IButton)
	{
		if (_clickLevel == 0)
		{
			_clickLevel++;
			for (currentButton in _valueByButton)
			{
				if (currentButton == button)
				{
					currentButton.selected = true;
					var value = _valueByButton.get(button);
					this.value = value;
				}
				else
				{
					currentButton.selected = false;
				}
			}
			_clickLevel--;
		}
	}
	
	function onChange(value:T)
	{
		if (_clickLevel == 0)
		{
			_clickLevel++;
			for (currentButton in _valueByButton)
			{
				var currentValue = _valueByButton.get(currentButton);
				if (currentValue == value)
				{
					currentButton.selected = true;
					break;
				}
			}
			_clickLevel--;
		}
	}
}